package com.bencordingley.remotecontrol;

import java.io.IOException;
import java.util.LinkedList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MediaBrowser extends Activity implements OnItemClickListener {

	private NetworkClient client;
	private LinkedList<String> history;

	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.media_browser);

		client = NetworkClient.connect(this);
		if (client == null) {
			Toast.makeText(this, "Error connecting to host", Toast.LENGTH_SHORT);
			finish();
		}

		ListView list = (ListView) findViewById(R.id.media_list);
		list.setOnItemClickListener(this);
		registerForContextMenu(list);
		if (savedInstanceState != null) {
			history = (LinkedList<String>) savedInstanceState.get("history");
		}
		if (history == null) {
			history = new LinkedList<String>();
			loadDirectory("");
		} else {
			loadDirectory(history.getLast());
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putSerializable("history", history);
	}

	private void loadDirectory(String dir) {
		loadDirectory(dir, true);
	}

	private void loadDirectory(String dir, boolean addToHistory) {
		final String directory;
		if (dir == null) {
			directory = "";
		} else {
			directory = dir;
		}
		if (addToHistory) {
			history.add(directory);
		}

		final Activity c = this;
		final ProgressDialog loading = ProgressDialog.show(this, "", "Loading", true);

		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				MediaItem[] files = (MediaItem[]) msg.obj;
				ArrayAdapter<MediaItem> a = new MediaBrowserAdapter(c, 0, files);
				ListView list = (ListView) findViewById(R.id.media_list);
				list.setAdapter(a);
				c.setTitle(directory);
				loading.dismiss();
			}
		};

		new Thread() {
			@Override
			public void run() {
				try {
					MediaItem[] files = client.listDirectory(directory);
					Message m = Message.obtain(handler);
					m.obj = files;
					m.sendToTarget();
				} catch (IOException e) {
					Toast.makeText(c, "Error loading directory", Toast.LENGTH_SHORT);
					e.printStackTrace();
				}
			}
		}.start();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		MediaItem mi = (MediaItem) parent.getItemAtPosition(position);
		if (mi.isDirectory()) {
			loadDirectory(mi.getLocation());
		} else {
			String[] playNowPlaylist = new String[] { mi.getLocation() };
			// put this in a thread and show a loading dialog
			try {
				client.setPlaylist(playNowPlaylist);
				client.play();
			} catch (IOException e) {
				Toast.makeText(this, "Error playing file", Toast.LENGTH_SHORT);
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		menu.add("Play now");
		menu.add("View details");
		menu.add("New playlist");
		menu.add("List of playlists");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (!history.getLast().equals("")) {
				history.removeLast();
				loadDirectory(history.getLast(), false);
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

}
